package nix.upload.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nix.commons.CommonUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload1Servlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 指定缓存大小及临时目录
		// DiskFileItemFactory factory = new DiskFileItemFactory(20 * 1024, new File("d:/temp"));
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 也可以使用request.setCharacterEncoding("utf-8")，setHeaderEncoding优先级更高
		sfu.setHeaderEncoding("utf-8");
		// 设置单个文件大小限制（200K）
		sfu.setFileSizeMax(200 * 1024);
		// 设置单个文件大小限制（5M）
		sfu.setSizeMax(1024 * 1024 * 5);
		try {
			List<FileItem> fileItemList = sfu.parseRequest(request);
			FileItem fi1 = fileItemList.get(0);
			FileItem fi2 = fileItemList.get(1);

			System.out.println("普通表单项：" + fi1.getFieldName() + "="
					+ fi1.getString("utf-8"));

			System.out.println("文件表单项：");
			System.out.println("Content-Type: " + fi2.getContentType());
			System.out.println("Size: " + fi2.getSize());
			
			// 有的浏览器上传的文件名是绝对路径，需要切割
			String fileName = fi2.getName();
			int index = fileName.lastIndexOf("\\");
			if (index != -1) {
				fileName = fileName.substring(index + 1);
			}		
			// 防止上传文件同名
			fileName = CommonUtils.uuid() + "_" + fileName;
			System.out.println("FileName: " + fi2.getName());

			// 保存目录哈希打散
			String root = this.getServletContext().getRealPath("/WEB-INF/files/");
			int hCode = fileName.hashCode();
			String hex = Integer.toHexString(hCode);
			
			File dirFile = new File(root,hex.charAt(0)+"/"+hex.charAt(1));
			dirFile.mkdirs();
			
			File descFile = new File(dirFile, fileName);
			fi2.write(descFile);

		} catch (FileUploadException e) {
			if (e instanceof FileUploadBase.FileSizeLimitExceededException) {
				request.setAttribute("msg", "您上传的单个文件大小超出了200K！");
				request.getRequestDispatcher("/upload/form1.jsp").forward(request, response);
			}
			if (e instanceof FileUploadBase.SizeLimitExceededException) {
				request.setAttribute("msg", "您提交的信息总大小超出了5M！");
				request.getRequestDispatcher("/upload/form1.jsp").forward(request, response);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

}
